<template>
  <el-dialog title="新增" width="450px"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             :visible.sync="dialogVisible"
             :before-close="handleClose" >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="类型">
        <el-input v-model="typeName" disabled class="form-item"></el-input>
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input-number v-model="form.code" :min="1" controls-position="right" class="form-item"></el-input-number>
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input v-model="form.value" class="form-item"></el-input>
      </el-form-item>
      <el-form-item label="顺序" prop="orderNo">
        <el-input-number v-model="form.orderNo" :min="0" controls-position="right" class="form-item"></el-input-number>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="submitBtnLoading" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'SaveDict',
  props: {
    visible: {
      type: Boolean
    },
    typeCode: {
      type: String,
      default: ''
    },
    typeName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      form: {},
      rules: {
        code: [
          {
            required: true,
            message: '编码不能为空',
            trigger: 'blur'
          }
        ],
        value: [
          {
            required: true,
            message: '值不能为空',
            trigger: 'blur'
          }
        ]
      },
      submitBtnLoading: false
    }
  },
  methods: {
    ...mapActions(['SaveDict']),
    handleClose(done) {
      this.$refs.form.resetFields()
      this.$emit('on-close')
      done()
    },
    close() {
      this.$refs.form.resetFields()
      this.$emit('on-close')
      this.dialogVisible = false
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitBtnLoading = true
          this.SaveDict({ typeCode: this.typeCode, data: this.form }).then(() => {
            this.submitBtnLoading = false
            this.$refs.form.resetFields()
            this.$emit('on-success')
            this.dialogVisible = false
          }).catch(() => {
            this.submitBtnLoading = false
          })
        }
      })
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.dialogVisible = val
      }
    }
  }
}
</script>

<style scoped>
  .form-item {
    width: 250px;
  }
</style>
